/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-use-before-define */
import DictTag from "@/components/DictTag";
import { DeleteOutlined, ExclamationCircleFilled, ExportOutlined, PlusOutlined } from "@ant-design/icons";
import { ActionType, PageContainer, ProColumns, ProTable } from "@ant-design/pro-components";
import { Button, FormInstance, Input, Modal, Space, message } from "antd";
import React, { useEffect, useRef, useState } from "react";
import AppForm, { AppFormData } from "./components/appForm";
import { getDict } from "@/services/api/module/system/dict";
import { getPageList, remove, save, update } from "@/services/api/module/system/application";
import CustomerTable from "@/components/CustomerTable";
import FilterDrawer from "@/components/FilterDrawer";
import { createTableColumns } from "./constants";
const { confirm } = Modal;
import { dict } from "@/utils/DictionaryCacheManager";

const AppTableList: React.FC = () => {
	const formTableRef = useRef<FormInstance>();
	const [appFormOpen, setAppFormOpen] = useState<boolean>(false);
	const actionRef = useRef<ActionType>();
	const [currentRowId, setCurrentRowId] = useState<number | undefined>(undefined);
	const [selectedRows, setSelectedRows] = useState<API.System.ApplicationVo[]>([]);
	const [statusOptions, setStatusOptions] = useState<any>([]);
	const [searchFormValue, setSearchFormValue] = useState<any>(undefined);
	const [searchValue, setSearchValue] = useState<any>(undefined);
	useEffect(() => {
		dict.getDict("sys_normal_disable").then(data => {
			setStatusOptions(data);
		});
	}, []);
	//数据请求
	const tableDataRequest = async (params: {} | undefined) => {
		return await getPageList({ ...searchFormValue, ...searchValue }).then((data: any) => {
			return data;
		});
	};
	const handleOnSearch = async (value: any) => {
		setSearchValue({
			userName: value
		});
		actionRef.current?.reload();
	};
	const handleColumnRemove = (record: any) => {
		handleRemove(record?.id);
	};
	const handleColumnEditor = (record: any) => {
		setAppFormOpen(true);
		setCurrentRowId(record?.id);
	};
	const columns = createTableColumns(statusOptions, handleColumnEditor, handleColumnRemove);
	// 删除
	const handleRemove = async (ids: number | Array<number>) => {
		return new Promise((reslove, reject) => {
			remove(ids)
				.then((res: any) => {
					message.success(res.msg);
					if (actionRef.current) {
						actionRef.current.reload();
					}
					reslove(true);
				})
				.catch(() => {
					reject(true);
				});
		});
	};
	// 删除警告提示
	const showRemoveConfirm = (ids: Array<number>, names: Array<string>) => {
		confirm({
			title: "警告",
			icon: <ExclamationCircleFilled />,
			content: `确认删除应用名称为：${names} 的应用吗?`,
			onOk() {
				return handleRemove(ids);
			},
			onCancel() {}
		});
	};
	// 保存
	const handleSave = async (values: AppFormData) => {
		return new Promise((resolve, reject) => {
			save({ ...values } as API.System.ApplicationBo)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	// 修改
	const handleUpdate = async (values: AppFormData) => {
		return new Promise((resolve, reject) => {
			update({ ...values } as API.System.ApplicationBo)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	// 关闭表单刷新列表
	const handleTableForm = async () => {
		setAppFormOpen(false);
		setCurrentRowId(undefined);
		actionRef?.current?.reload();
	};

	return (
		<>
			<CustomerTable<API.System.ApplicationVo>
				actionRef={actionRef}
				formRef={formTableRef}
				rowKey="id"
				key="appList"
				request={tableDataRequest}
				search={false}
				tableStyle={{ minHeight: "calc(100vh - 200px)" }}
				toolbar={{
					search: (
						<Space>
							<Input.Search placeholder="通过用户账号搜索" allowClear style={{ width: 280 }} onSearch={handleOnSearch} />
							<FilterDrawer
								columns={columns}
								tableActionRef={actionRef}
								onReset={() => {
									setSearchFormValue(undefined);
									actionRef?.current?.reload();
								}}
								onSubmit={(values: any) => {
									setSearchFormValue(values);
									actionRef?.current?.reload();
								}}
							/>
						</Space>
					)
				}}
				toolBarRender={() => [
					<Button
						type="primary"
						key="add"
						onClick={async () => {
							setAppFormOpen(true);
						}}
					>
						<PlusOutlined /> 创建应用
					</Button>
					// <Button
					// 	type="primary"
					// 	key="remove"
					// 	danger
					// 	// hidden={}
					// 	onClick={async () => {
					// 		if (selectedRows.length <= 0) {
					// 			message.warning("请选择一条或多条数据");
					// 			return;
					// 		}
					// 		//todo 如果选中包含超级管理员也没办法显示，需要做
					// 		// showRemoveConfirm(
					// 		// 	Array.from(selectedRows, ({ id }) => id),
					// 		// 	Array.from(selectedRows, ({ appName }) => appName)
					// 		// );
					// 	}}
					// >
					// 	<DeleteOutlined />
					// 	批量删除
					// </Button>
				]}
				columns={columns}
				rowSelection={{
					onChange: (_, selectedRows) => {
						setSelectedRows(selectedRows);
					}
				}}
				tableAlertRender={false}
			/>
			<AppForm
				open={appFormOpen}
				onSubmit={async (values: AppFormData) => {
					return values?.id ? await handleUpdate(values) : await handleSave(values);
				}}
				idValue={currentRowId}
				onCancel={() => {
					setCurrentRowId(undefined);
					setAppFormOpen(false);
				}}
				statusOptions={statusOptions}
			/>
		</>
	);
};

export default AppTableList;
